<template>
	<view class="home">
		<!-- 顶部地址+搜索栏（优化布局，避免溢出） -->
		<view class="top-header-bar">
			<view class="address-area">
				<uni-icons type="location" size="26" color="#333"></uni-icons>
				<text class="address-text">{{ formatCompactAddress(currentAddress) }}</text>
				<uni-icons type="arrow-right" size="22" color="#333"></uni-icons>
				<view class="header-icons">
					<uni-icons type="refresh" size="26" color="#333" @click="refreshAddress"></uni-icons>
					<uni-icons type="more" size="26" color="#333" @click="showMoreOptions"></uni-icons>
				</view>
			</view>

			<view class="search-area">
				<view class="search-input">
					<uni-icons type="search" size="26" color="#999"></uni-icons>
					<input type="text" v-model="searchText" placeholder="搜索商家或美食" placeholder-class="placeholder-style"
						@input="handleSearchInput" @confirm="handleSearchConfirm" />
					<uni-icons v-if="searchText" type="clear" size="20" color="#999" class="clear-icon"
						@click="clearSearch"></uni-icons>
				</view>
				<button class="search-btn" @click="handleSearch">搜索</button>
			</view>
		</view>

		<!-- 搜索结果页面 -->
		<view v-if="showSearchResult" class="search-result-container">
			<view class="search-result-header">
				<text class="result-title">搜索结果</text>
				<text class="result-count">找到 {{ searchResults.length }} 个结果</text>
				<view class="close-btn" @click="closeSearchResult">关闭</view>
			</view>
			
			<!-- 商品列表 -->
			<view class="goods-list">
				<view 
					v-for="goods in searchResults" 
					:key="goods.goodsId" 
					class="goods-card"
					:class="{ 'goods-offline': goods.isOnSale === 0 }"
					@click="goToGoodsDetail(goods)"
				>
					<image :src="handleImgURL(goods.goodsImg)" mode="aspectFill" class="goods-img" lazy-load></image>
					<view class="offline-tag" v-if="goods.isOnSale === 0">已下架</view>
					<view class="goods-info">
						<text class="goods-name">{{ goods.goodsName }}</text>
						<text class="goods-spec" v-if="goods.categoryName">{{ goods.categoryName }}</text>
						<view class="goods-price-wrap">
							<text class="goods-price">¥{{ goods.goodsPrice }}</text>
							<text class="goods-sales" v-if="goods.salesNum">销量{{ goods.salesNum }}</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 无结果提示 -->
			<view v-if="searchResults.length === 0 && searchText" class="no-result">
				<uni-icons type="search" size="60" color="#ccc"></uni-icons>
				<text class="no-result-text">暂无搜索结果</text>
				<text class="no-result-desc">换个关键词试试吧</text>
			</view>
		</view>

		<!-- 正常首页内容（搜索时隐藏） -->
		<view v-else>
			<!-- 轮播图（移除顶部间距，无缝衔接） -->
			<view class="carousel-container">
				<home-carousel :list="carouselItems"></home-carousel>
			</view>

			<!-- 快捷入口（紧凑排版） -->
			<view class="enter-container">
				<home-enter></home-enter>
			</view>

			<!-- 分类导航（优化间距） -->
			<view class="category-container">
				<scroll-view scroll-x class="category-scroll" show-scrollbar="false">
					<view class="category-item" v-for="(item, index) in categoryList" :key="index" @click="searchByCategory(item.name)">
						<image :src="item.icon" mode="widthFix"></image>
						<text>{{ item.name }}</text>
					</view>
				</scroll-view>
			</view>

			<!-- 商品推荐（无缝衔接分类） -->
			<view class="goods-container">
				<home-label :recommended="recommendedItems"></home-label>
			</view>
		</view>

	</view>
</template>

<script>
	import * as HomeAPI from "@/api/home.js";
	import HomeEnter from "./components/homeEnter.vue";
	import HomeCarousel from "./components/homeCarousel.vue";
	import HomeLabel from "./components/homeLabel.vue";
	import { queryPage } from '@/api/goods.js';
	import { baseUrl } from '@/utils/config.js';

	export default {
		name: "home",
		components: {
			HomeEnter,
			HomeCarousel,
			HomeLabel
		},
		data() {
			return {
				currentAddress: "宁大学生村",
				searchText: "",
				// 搜索相关状态
				showSearchResult: false,
				searchResults: [],
				searchTimer: null,
				// 原有数据
				carouselItems: [],
				recommendedItems: [],
				newArrialItems: [],
				topSaleItems: [],
				categoryList: [{
						name: "奶茶",
						icon: "/static/category/milk.png"
					},
					{
						name: "汉堡",
						icon: "/static/category/hamburger.png"
					},
					{
						name: "炸鸡",
						icon: "/static/category/chicken.png"
					},
					{
						name: "披萨",
						icon: "/static/category/pizza.png"
					},
					{
						name: "快餐",
						icon: "/static/category/fastfood.png"
					},
					{
						name: "早餐",
						icon: "/static/category/breakfast.png"
					}
				]
			};
		},
		created() {
			this.getHomeData();
			this.loadDefaultAddress();
		},
		methods: {
			getHomeData() {
				HomeAPI.getHomeData()
					.then(result => {
						if (!result?.data) throw new Error("接口格式异常");
						const data = result.data;
						Object.assign(this, {
							carouselItems: data.carouselList || [],
							recommendedItems: data.recommendGoodsList || [],
							newArrialItems: data.newArrialList || [],
							topSaleItems: data.topSaleList || []
						});
					})
					.catch(err => {
						console.error('数据加载失败：', err);
						uni.showToast({
							title: '加载失败：' + err.message,
							icon: 'none'
						});
						this.carouselItems = [];
					});
			},
			formatCompactAddress(fullAddress) {
				if (!fullAddress) return '';
				const regex = /(?:省|市|自治区|壮族自治区|维吾尔自治区|回族自治区|蒙古族自治区)([^\s]+?市|州|盟)?([^\s]+?区|县|旗)([^\s]+)/;
				const match = fullAddress.match(regex);
				if (match) {
					return `${match[2] || ''}${match[3] || ''}`.trim();
				}
				return fullAddress;
			},
			loadDefaultAddress() {
				const addressList = uni.getStorageSync('addressList') || [];
				const defaultAddr = addressList.find(item => item.isDefault);
				if (defaultAddr) {
					const fullAddress =
						`${defaultAddr.province}${defaultAddr.city}${defaultAddr.county}${defaultAddr.addressDetail}`;
					this.currentAddress = fullAddress;
				}
			},
			refreshAddress() {
				uni.showLoading({
					title: '刷新中...'
				});
				setTimeout(() => {
					const addressList = uni.getStorageSync('addressList') || [];
					if (addressList.length === 0) {
						uni.hideLoading();
						uni.showToast({
							title: '暂无地址可更新',
							icon: 'none'
						});
						return;
					}
					const randomAddr = addressList[Math.floor(Math.random() * addressList.length)];
					this.currentAddress =
						`${randomAddr.province}${randomAddr.city}${randomAddr.county}${randomAddr.addressDetail}`;
					uni.hideLoading();
					uni.showToast({
						title: `地址已更新为：${this.formatCompactAddress(this.currentAddress)}`,
						icon: 'none'
					});
				}, 800);
			},
			showMoreOptions() {
				uni.showActionSheet({
					itemList: ['切换地址', '设置', '帮助中心'],
					success: (res) => {
						if (res.tapIndex === 0) uni.navigateTo({
							url: '/pages/address/addressList'
						});
						if (res.tapIndex === 1) uni.navigateTo({
							url: '/pages/user/setting'
						});
					}
				});
			},
			handleSearchInput() {
				// 防抖搜索，输入时延迟执行搜索
				clearTimeout(this.searchTimer);
				this.searchTimer = setTimeout(() => {
					if (this.searchText.trim()) {
						this.performSearch();
					}
				}, 500);
			},
			handleSearchConfirm() {
				// 回车键搜索
				clearTimeout(this.searchTimer);
				this.performSearch();
			},
			handleSearch() {
				// 点击搜索按钮
				this.performSearch();
			},
			// 执行搜索
			async performSearch() {
				if (!this.searchText.trim()) {
					uni.showToast({
						title: '请输入搜索内容',
						icon: 'none'
					});
					return;
				}
				
				try {
					uni.showLoading({
						title: '搜索中...'
					});
					
					const params = {
						pageNum: 1,
						pageSize: 50, // 首页搜索可以显示更多结果
						keyword: this.searchText.trim(),
						orderBy: 'sales_num DESC' // 默认按销量排序
					};
					
					console.log("搜索参数：", params);
					
					const res = await queryPage(params);
					
					if (![200, 0].includes(res?.code) || !res?.data) {
						throw new Error(res?.msg || '搜索失败');
					}
					
					const goodsArray = res.data.list || [];
					const formatData = goodsArray.map(goods => ({
						...goods,
						goodsPrice: goods.goodsPrice || 0,
						salesNum: goods.salesNum || 0,
						isOnSale: goods.isOnSale ?? 1
					}));
					
					this.searchResults = formatData;
					this.showSearchResult = true;
					
					uni.hideLoading();
					
					if (formatData.length > 0) {
						uni.showToast({
							title: `找到 ${formatData.length} 个结果`,
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: '暂无搜索结果',
							icon: 'none'
						});
					}
					
				} catch (err) {
					uni.hideLoading();
					uni.showToast({
						title: err.message,
						icon: 'none',
						duration: 2000
					});
					this.searchResults = [];
				}
			},
			// 按分类搜索
			searchByCategory(categoryName) {
				this.searchText = categoryName;
				this.performSearch();
			},
			// 清空搜索
			clearSearch() {
				this.searchText = '';
				this.showSearchResult = false;
				this.searchResults = [];
			},
			// 关闭搜索结果
			closeSearchResult() {
				this.showSearchResult = false;
				this.searchText = '';
				this.searchResults = [];
			},
			// 处理图片URL
			handleImgURL(url) {
				if (!url) return '/static/images/default-goods.png';
				return url.includes('http') ? url : `${baseUrl}${url}`;
			},
			// 跳转到商品详情
			goToGoodsDetail(goods) {
				// 已下架商品提示不跳转
				if (goods.isOnSale === 0) {
					uni.showToast({
						title: '商品已下架',
						icon: 'none',
						duration: 1500,
						mask: true
					});
					return;
				}
				
				// 上架商品：正常跳转
				uni.navigateTo({
					url: `/pages/goods/goodsDetail?goodsId=${goods.goodsId}`
				});
			}
		}
	};
</script>

<style scoped>
	/* 原有样式保持不变 */
	.home {
		background-color: #fff;
		min-height: 100vh;
		padding-bottom: 120rpx;
		margin: 0;
		padding-top: 0;
	}

	.top-header-bar {
		background-color: #FFD900;
		padding: 16rpx 24rpx;
		box-sizing: border-box;
		overflow: hidden;
	}

	.address-area {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 12rpx;
		line-height: 1;
	}

	.address-text {
		font-size: 30rpx;
		color: #333;
		margin: 0 10rpx;
		flex: 1;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		font-weight: 500;
		line-height: 1.2;
	}

	.header-icons {
		display: flex;
		gap: 24rpx;
		align-items: center;
	}

	.search-area {
		display: flex;
		align-items: center;
		gap: 0;
		height: 76rpx;
	}

	.search-input {
		display: flex;
		align-items: center;
		background: #fff;
		border-radius: 36rpx 0 0 36rpx;
		padding: 0 24rpx;
		flex: 1;
		height: 100%;
		gap: 16rpx;
		position: relative;
	}

	.search-input input {
		margin-left: 0;
		font-size: 30rpx;
		flex: 1;
		height: 100%;
		line-height: normal;
	}

	.clear-icon {
		position: absolute;
		right: 24rpx;
	}

	.search-btn {
		background-color: #FF7D00;
		color: #fff;
		font-size: 30rpx;
		padding: 0 36rpx;
		border-radius: 0 36rpx 36rpx 0;
		line-height: normal;
		height: 100%;
		font-weight: 500;
	}

	.placeholder-style {
		color: #999;
		font-size: 30rpx;
	}

	.carousel-container {
		width: 100%;
		margin-top: 0;
		padding-top: 0;
		line-height: 0;
	}

	::v-deep .carousel-container>>>.uni-swiper {
		margin-top: 0 !important;
		padding-top: 0 !important;
	}

	.enter-container {
		padding: 20rpx 0;
		background-color: #fff;
	}

	.category-container {
		background-color: #fff;
		padding: 16rpx 24rpx;
		border-top: 1px solid #f5f5f5;
	}

	.category-scroll {
		white-space: nowrap;
	}

	.category-item {
		display: inline-block;
		width: 140rpx;
		text-align: center;
		margin-right: 20rpx;
	}

	.category-item image {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-bottom: 12rpx;
	}

	.category-item text {
		font-size: 26rpx;
		color: #333;
		display: block;
		white-space: normal;
		font-weight: 500;
	}

	.goods-container {
		background-color: #fff;
	}

	/* 搜索结果样式 */
	.search-result-container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.search-result-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx;
		background: #fff;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.result-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.result-count {
		font-size: 26rpx;
		color: #999;
		flex: 1;
		margin-left: 24rpx;
	}

	.close-btn {
		font-size: 28rpx;
		color: #FF7D00;
	}

	/* 商品列表样式（参考店铺详情页） */
	.goods-list {
		padding: 24rpx;
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 24rpx;
	}

	.goods-card {
		background-color: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		position: relative;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.goods-offline {
		opacity: 0.6;
	}

	.goods-img {
		width: 100%;
		height: 200rpx;
		object-fit: cover;
	}

	.offline-tag {
		position: absolute;
		top: 16rpx;
		left: 16rpx;
		background-color: #999;
		color: #fff;
		font-size: 20rpx;
		padding: 4rpx 12rpx;
		border-radius: 8rpx;
	}

	.goods-info {
		padding: 20rpx;
	}

	.goods-name {
		font-size: 28rpx;
		color: #333;
		line-height: 1.4;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		margin-bottom: 12rpx;
	}

	.goods-spec {
		font-size: 22rpx;
		color: #999;
		display: block;
		margin-bottom: 12rpx;
	}

	.goods-price-wrap {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.goods-price {
		font-size: 28rpx;
		font-weight: 600;
		color: #FF7D00;
	}

	.goods-sales {
		font-size: 22rpx;
		color: #999;
	}

	.no-result {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 120rpx 0;
		background: #fff;
		border-radius: 16rpx;
		margin: 40rpx 24rpx;
	}

	.no-result-text {
		font-size: 32rpx;
		color: #999;
		margin: 24rpx 0 12rpx;
	}

	.no-result-desc {
		font-size: 26rpx;
		color: #ccc;
	}

	.bottom-nav {
		display: flex;
		justify-content: space-around;
		align-items: center;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 120rpx;
		background: #fff;
		box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.06);
		z-index: 999;
	}

	.nav-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 8rpx;
	}

	.nav-item.active .nav-text {
		color: #FF7D00;
	}

	.nav-text {
		font-size: 24rpx;
		color: #666;
	}
</style>